<template>
  <!-- 问题信息弹窗 -->
  <dialog-form v-bind="$attrs" v-on="$listeners" ref="dialogForm" :form="dialogForm" :editModel="dialogEditModel" @changeRules="changeRules"
    :width="1000" :formList="dialogFormList" :visible.sync="visible" :isEmit="false"
    :class="[isFlagcheckType ? 'isFlagcheckType' : '',bcRules?'deFlagcheckType':'',pubDialogForm?'pubDialogForm':'',wtjbClassName]"   
    @confirm="(e) => $emit('handleConfirm', e)">
    <!-- isFlagcheckType 为管理行为，deFlagcheckType整改单位 stCsClassName为补充的一般问题，xwZlClassName补充的管理行为一般问题-->
<!--    检查类型-->
    <template slot="checkType" slot-scope="scoped">
      <a-select
              show-search
              placeholder="请选择"
              allowClear
              v-model="scoped.data.form.checkType"
      >
        <a-select-option :value="item.value" v-for="item in checkTypeList" :key="item.value">
          {{item.name}}
        </a-select-option>
      </a-select>
    </template>
<!--    工程类别-->
    <template slot="projectTypeId" slot-scope="scoped">
      <a-select
              show-search
              placeholder="请选择"
              v-model="scoped.data.form.projectTypeId"
              @change="handleProjectTypeChange"
      >
        <a-select-option :value="item.projectTypeId" v-for="item in projectTyoeList" :key="item.projectTypeId">
          {{item.projectTypeName}}
        </a-select-option>
      </a-select>
    </template>
    <template slot="problemId" slot-scope="scoped">
      <a-tree-select
              v-model="scoped.data.form.problemId"
              show-search
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择"
              allow-clear
              :treeData="problemList"
              treeNodeFilterProp='title'
              :replaceFields="{children:'children', title:'name', key:'id', value: 'id' }"
              @change="handleTreeChange"
      >
      </a-tree-select>
    </template>
    <template slot="coordinate" slot-scope="scoped">
      <span
        v-if="scoped.data.form.problem && scoped.data.form.problem.coordinate && scoped.data.form.problem.coordinate.length"
        class="del_btn">已选</span>
      <a-button class="ml12" :loading="btnLoading" type="primary" icon="paper-clip"
        @click="handleChoose(scoped.data.form)">选择具体位置</a-button>
      <!-- 打点图 -->
      <PreView :isEdit="true" :isDownload="false" :pointer.sync="scoped.data.form.coordinate"
        :preview-image="previewImage" :visible.sync="previewVisible"
        @getPointer="(e) => handlePoints(e, scoped.data.form)" />
    </template>
  </dialog-form>
</template>

<script>
import { scoringType } from '@/api/quality/quality' // 质量api
import { getNodeById } from '@/api/complaint' // 维保api
import office from '@/api/office/asset' // 办公api
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople' // 人员选择器
import Selector from '@/components/Select/Selector' // 人员选择器
import DialogForm from '@/components/DialogForm' // 添加问题弹窗
import SelectATtree from '@/components/Select/SelectATtree' // 通用搜索树
import SelectTreeDistrict from '@/components/Select/SelectTreeDistrict' // 检查区域
import SelectProblemTypeTree from '@/components/Select/SelectProblemTypeTree' // 质量问题描述
import SelectDutyArea from '@/components/Select/SelectDutyArea' // 整改单位
import PreView from '@/components/PreView' // 检查问题具体位置（打点）
import { projectType,subItem} from '@/api/quality/currency' // api
import SelectProjectType from '@/components/Select/SelectProjectType'
import { getProjectTypes } from '@/api/project/projects' // 工程类别
import  { getTechnicalProblemList } from "@/api/technology"
export default {
  name: 'DialogProblem',
  components: {
    DialogForm,
    PreView,
    SelectATtree
  },
  props: {
    // 弹窗操作类型：U 新增；E 编辑
    dialogEditModel: {
      type: String,
      default: () => 'U'
    },
    // 外部表单
    dialogForm: {
      type: Object,
      default: () => ({})
    },
    //选中的受检单位岗位信息
    postData: {
      type: Object,
      default: () => { }
    },
  },
  data() {
    return {
      checkTypeList: [
        {
          name: '危大工程管理',
          value: '危大工程管理'
        },
        {
          name: '施组方案管理',
          value: '施组方案管理'
        },
        {
          name: '双优化管理',
          value: '双优化管理'
        },
        {
          name: '设计文件管理',
          value: '设计文件管理'
        },
        {
          name: '计量设备管理',
          value: '计量设备管理'
        },
        {
          name: '技术复核管理',
          value: '技术复核管理'
        },
        {
          name: '施工平面布置管理',
          value: '施工平面布置管理'
        },
        {
          name: '技术讲座',
          value: '技术讲座'
        },
        {
          name: '技术管理策划',
          value: '技术管理策划'
        }
      ],
      btnLoading: false, // 选择具体位置按钮加载控件
      visible: false, // 弹窗控件
      previewVisible: false, // 打点图弹窗控件
      previewImage: [], // 打点图
      options: [], // 工程品质类型列表
      rectifierCompany: {}, // 整改单位业务对象
      fbfxTreeData:[],  //分部分项数据data
      productType:[],  //工程类别数据
      tageCode:null, //受检单位的code 
      isFlagcheckType:true,   //是否是 false工程实体和措施 或 true管理行为和资料
      bcRules:false, // 业务待办补充的校验
      pubDialogForm:true,
      isBcRules:false, //是否是补充
      isManagement:false, // 是否是管理行为
      projectTyoeList: [], //工程类别
      problemList: [] // 问题描述
    }
  },
  mounted() {
    this.getProjectTypes()
  },
  watch:{
   visible(e) {
     this.tageCode = this.dialogForm?.tageCode;
     if(e) {
       this.$nextTick(()=>{
         setTimeout(()=>{
           this.$set(this.$refs.dialogForm.forms,'rectifierCompanyName', this.dialogForm.inspectedUnitName)  //inspectedUnitId
           this.$set(this.$refs.dialogForm.forms,'rectifierCompanyId', this.dialogForm.inspectedUnitId)  //inspectedUnitId
           if(this.$refs.dialogForm.forms.projectTypeId) {
             this.handleProjectTypeChange(this.$refs.dialogForm.forms.projectTypeId, false)
           }
               if(this.$route.query.noticeType == '406'&&!this.$refs.dialogForm.forms.projectTypeId&&this.projectTyoeList.length) {
                  const projectTypeId = this.projectTyoeList[0].projectTypeId
                   this.$set(this.$refs.dialogForm.forms,'projectTypeId', projectTypeId)
                   this.handleProjectTypeChange(projectTypeId, false)
               }
         }, 20)
       })
     }
    }
  },
  computed: {
    // 弹窗配置项
    dialogFormList() {
      let that = this;
      return [
        // 弹窗表单配置
        {
          keyName: 'checkType',
          label: '检查类别',
          slot: true
        },
        {
          keyName: 'typeId',
          label: '检查类型',
          type: Selector,
          attrs: {
            selectType: '0',
            isDefault: !this.$refs.dialogForm?.forms?.typeId?true:false,
            isDefaultTypeId:!this.$refs.dialogForm?.forms?.typeId?true:false,
            attr: {
              code: '1',
            }
          },
          onChange(obj) {
            that.$refs.dialogForm.forms.typeName = obj.name
          }
        },
        {
          keyName: 'respAreaId',
          label: '检查区域',
          type: SelectTreeDistrict,
          attrs: {
            id: this.dialogForm.projectId,
            isShowSearch: false,
            isFirstNode: true,
            deleteProjectId:true,
            finalNode:true,
          },
          change: (value, label) => {
            that.$set(that.$refs.dialogForm.forms,'newRespAreaId',value) //新加一个字段用于联动
            that.$refs.dialogForm.forms.respAreaName = label[0] || ''
            // 重置整改人和责任人列表及表单
            // this.rectifierCompany = {}
            that.$set(that.$refs.dialogForm.forms, 'rectifierId', void 0)
            that.$set(that.$refs.dialogForm.forms, 'dutyId', void 0)
            that.$set(that.$refs.dialogForm.forms, 'coordinate', void 0)
            if (!that.$refs.dialogForm.forms.problem) {
              that.$set(that.$refs.dialogForm.forms, 'problem', { coordinate: void 0 })
            } else {
              that.$set(that.$refs.dialogForm.forms.problem, 'coordinate', void 0)
            }
          }
        },
        {
          keyName: 'rectifierCompanyName',
          label: '整改单位',
          type: 'BaseInput',
          disabled: true,
        },
        {
          keyName: 'projectTypeId',
          label: '工程类别',
          slot: true
        },
        {
          keyName: 'subProjectId',
          label: '分部分项',
          placeholder:'请选择',
          type: SelectATtree,
          attrs: {
            treeData: this.fbfxTreeData,
          },
          change: (value, label) => {
            if (label[0]) {
              that.$refs.dialogForm.forms.subProjectName = label[0] || ''
              that.$refs.dialogForm.forms.subProjectId = value
              that.$set(that.dialogForm, 'subProjectId', value)
            }
          },
        },
        {
          keyName: 'checkDescribe',
          label: '具体部位',
          type: 'BaseInput'
        },
        {
          keyName: 'problemId',
          label: '问题描述',
          slot: true
        },
        {
          keyName: 'problemSupply',
          label: '问题补充',
          type: 'BaseTextarea'
        },
        {
          keyName: 'level',
          label: '问题级别',
          type: 'a-radio-group',
          data: [
            // 由于后端只要汉字不要id，所有没有请求枚举，枚举接口为cscec-quality-business/quality/types-label?type=40
            {
              value: '重大',
              label: '重大'
            },
            {
              value: '较大',
              label: '较大'
            },
            {
              value: '一般',
              label: '一般'
            }
          ]
        },
        {
          keyName: 'rectifyTerm',
          label: '整改期限',
          type: 'BaseInput',
          disabled: true
        },
        {
          keyName: 'rectifierId',      // 公司级
          label: '整改人',
          type: ASelectOrgPeople,
          attrs: {
            isBlur: true,
            optionKey: 'id',
            keyValue: 'inspectedUnitId', // 联动字段名
            orgId: this.dialogForm.inspectedUnitId, // 联动表单
            isRank:true,
          },
            onSelectChange: (e) => {
              that.$refs.dialogForm.forms.rectifierName = e?.name
          }
        },
        {
          keyName: 'dutyId',   // 公司级
          label: '责任人',
          type: ASelectOrgPeople,
          attrs: {
            isBlur: true,
            optionKey: 'id',
            keyValue: 'inspectedUnitId', // 联动字段名
            orgId: this.dialogForm.inspectedUnitId, // 联动表单
            isRank:true,
          },
          onSelectChange: (e) => {
            that.$refs.dialogForm.forms.dutyName = e?.name
          }
        },
        {
          keyName: 'reCheckId',
          label: '复查人',
          type: ASelectOrgPeople,
          attrs: {
            isBlur: true,
            optionKey: 'id',
            keyValue: 'inspectedUnitId', // 联动字段名
            orgId: this.dialogForm.inspectedUnitId, // 联动表单
            isRank:true,
          },
          onSelectChange: (e) => {
            that.$refs.dialogForm.forms.reCheckName = e?.name
          }
        },
        {
          keyName: 'sendUserIds',
          label: '抄送',
          type: ASelectOrgPeople,
          attrs: {
            isBlur: true,
            mode: 'multiple',
            maxTagCount: 1,
            optionKey: 'id',
            orgId: this.dialogForm.inspectedUnitId, // 联动表单
            isRank:true,
          }
        },
        {
          keyName: 'coordinate',
          label: '检查（问题）具体位置',
          slot: true
        },
        {
          keyName: 'fileArrays',
          label: '影像资料',
          type: 'uploadFile',
          businessCode: 'QM01',
          remark:'请上传原件，支持格式：.jpg .png .mp4 .mov',
          attrs: {
            delRequest: false,
            uploadType: 'uploadImgAndVideo',
            editModel: this.dialogEditModel,
            isMultiple: true,
            useAccept: true,
            isUploadImgAndVideo:true,
            isUploadImgAndVideoLog:true,
            accept: ".jpg,.png,.mov, .mp4"
          },
          span: 16
        }
      ]
    },
    wtjbClassName(){
       let flag = '';
       if(this.isBcRules){  //为补充
             flag = 'xwziClassName'
       }else{
        flag = '';
       }
       return flag;
    }
  },
  methods: {
    getProjectTypes() {
      getProjectTypes().then((res) => {
        this.projectTyoeList = res.data?.filter(i => i.status*1 === 1)
        this.$nextTick(()=>{
          setTimeout(()=>{
            if(this.$route.query.noticeType == '406'&&!this.$refs.dialogForm.forms.projectTypeId&&this.projectTyoeList.length) {
              const projectTypeId = this.projectTyoeList[0].projectTypeId
              this.$set(this.$refs.dialogForm.forms,'projectTypeId', projectTypeId)
              this.handleProjectTypeChange(projectTypeId, false)
            }
          }, 20)
        })
      })
    },
    handleProjectTypeChange(val, isAdd) {
      if(isAdd) {
        this.$set(this.$refs.dialogForm.forms,'problemId', null)
        this.$set(this.$refs.dialogForm.forms,'subProjectId', null)
      }
      const obj = this.projectTyoeList.find(item=>val===item.projectTypeId)
      this.$set(this.$refs.dialogForm.forms,'projectTypeName', obj.projectTypeName)

      this.getTechnicalProblemList(val)
      this.getSubItemData(val)
    },
    getTechnicalProblemList(id) {
      getTechnicalProblemList({id}).then(res=>{
        this.recurrenceTree(res.data)
        this.problemList = res.data
      })
    },
    recurrenceTree(data) {
      data.forEach(item=>{
        if(item.type==1) {
          item.disabled = true
        }
        if(item.children&&item.children.length>0) {
          this.recurrenceTree(item.children)
        }
      })
    },
    handleTreeChange(value, label) {
      this.$set(this.$refs.dialogForm.forms,'problemName', label[0])
    },
    changeRules(val){
       if(val.isBcRules){  //是否是补充
          this.isBcRules = val.isBcRules;
          this.bcRules  = true;
       }else{
          this.bcRules  = false;
       }
    },
    /**
     * @description: form：表单
     */
    handleChoose(form) {
      if (!form.respAreaId) {
        this.$message.warning('请先选择检查区域！')
        return
      }
      this.btnLoading = true
      // 先请求检查区域施工图，再打开点位图
      getNodeById(form.respAreaId)
        .then((res) => {
          if (res.code === 200 && res.data) {
            // 映射施工图到点位背景
            this.previewImage = [res.data]
            // 打开弹窗
            this.previewVisible = true
          } else {
            this.$message.warning('请先添加检查区域的施工图！')
          }
        })
        .finally(() => {
          this.btnLoading = false
        })
    },
    /**
     * @description: 转化弹窗表单检查（问题）具体位置坐标，格式化成x,y:x,y字符形式
     * @param {*} e：点位列表
     * @param {*} form：表单
     */
    handlePoints(e, form) {
      // console.log(arguments)
      if (!form.problem) {
        this.$set(form, 'problem', { coordinate: e?.map((i) => i.x + ',' + i.y)?.join(';') })
      } else {
        this.$set(form.problem, 'coordinate', e?.map((i) => i.x + ',' + i.y)?.join(';'))
      }
      this.$set(form, 'coordinate', e)
    },
    // 获取工程类别数据
    getProductType(val){
      let obj = val?{id:val}:{};
       projectType.getList(obj).then((res)=>{
         if(res.code == 200){
             this.productType = res.data.filter((item)=>item.status*1===1);
         }
       })
    },
    //获取工程资料或管理行为分部分项
     getSubItemData(id){
      let args = {
          sources: 0,
          id,
      }
      id && subItem.getList(args).then((res)=>{
        if(res.code == 200){
          this.fbfxTreeData = res?.data[0]?.children || [];
        }
      })
    },

  }
}
</script>
<style scoped lang="less">
@deep: ~'>>>';
.isFlagcheckType{
  @{deep} .ant-row-flex{
     .ant-col:nth-child(3), .ant-col:nth-child(6){
      .requiredFormItem{
        .ant-select{
          .ant-select-selection{
            background-color: #fff;
            border: 1px solid #d9d9d9;
          }
        }
      }
     }
  }
}
.deFlagcheckType{
  @{deep} .ant-row-flex{
     .ant-col:nth-child(4){
       .ant-select{
          .ant-select-selection{
            border-color: #e4ac0b;
            background-color: #FFF9E8;
          }
        }
     }
  }
}
.pubDialogForm{
    @{deep} .ant-row-flex{
     .ant-col:nth-child(4){
       .ant-select-selection__placeholder{
        display: block!important;
       }
     }
  }
}
.stcsClassName{
    @{deep} .ant-row-flex{
     .ant-col:nth-child(9){
      .ant-form-item-required::before{
       opacity: 1;
      }
     }
      .ant-col:nth-child(3), .ant-col:nth-child(5), .ant-col:nth-child(7), .ant-col:nth-child(8){
       .ant-select{
          .ant-select-selection{
            border-color: #e4ac0b;
            background-color: #FFF9E8;
          }
        }
     }
  }
}
.xwziClassName{
    @{deep} .ant-row-flex{
     .ant-col:nth-child(10){
      .ant-form-item-required::before{
       opacity: 1;
      }
     }
  }
}
</style>